home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / share / perl5 / RPC / XML.pm
Text File  |  2008-04-09  |  51KB  |  1,704 lines

  1. ###############################################################################
  2. #
  3. # This file copyright (c) 2001-2008 Randy J. Ray, all rights reserved
  4. #
  5. # See "LICENSE" in the documentation for licensing and redistribution terms.
  6. #
  7. ###############################################################################
  8. #
  9. #   $Id: XML.pm 343 2008-04-09 09:54:36Z rjray $
  10. #
  11. #   Description:    This module provides the core XML <-> RPC conversion and
  12. #                   structural management.
  13. #
  14. #   Functions:      This module contains many, many subclasses. Better to
  15. #                   examine them individually.
  16. #
  17. #   Libraries:      RPC::XML::base64 uses MIME::Base64
  18. #
  19. #   Global Consts:  $VERSION
  20. #
  21. ###############################################################################
  22.  
  23. package RPC::XML;
  24.  
  25. use 5.005;
  26. use strict;
  27. use vars qw(@EXPORT @EXPORT_OK %EXPORT_TAGS @ISA $VERSION $ERROR
  28.             %xmlmap $xmlre $ENCODING $FORCE_STRING_ENCODING);
  29. use subs qw(time2iso8601 smart_encode bytelength);
  30.  
  31. # The following is cribbed from SOAP::Lite, tidied up to suit my tastes
  32. BEGIN
  33. {
  34.     no strict 'refs';
  35.  
  36.     eval "use bytes";
  37.     # Re-worked this passage to continue supporting perl 5.005. It tried to
  38.     # compile the "use bytes" in the second block even if the conditional never
  39.     # travelled that path. So, explicit eval strings for everyone.
  40.     if ($@)
  41.     {
  42.         eval 'sub bytelength { length(@_ ? $_[0] : $_) }';
  43.     }
  44.     else
  45.     {
  46.         eval 'sub bytelength { use bytes; length(@_ ? $_[0] : $_) }';
  47.     }
  48.  
  49.     %xmlmap = ( '>' => '>',   '<' => '<', '&' => '&',
  50.                 '"' => '"', "'" => ''');
  51.     $xmlre = join('', keys %xmlmap); $xmlre = qr/([$xmlre])/;
  52.  
  53.     # Default encoding:
  54.     $ENCODING = 'us-ascii';
  55.  
  56.     # force strings?
  57.     $FORCE_STRING_ENCODING = 0;
  58. }
  59.  
  60. require Exporter;
  61.  
  62. @ISA = qw(Exporter);
  63. @EXPORT_OK = qw(time2iso8601 smart_encode bytelength
  64.                 RPC_BOOLEAN RPC_INT RPC_I4 RPC_DOUBLE RPC_DATETIME_ISO8601
  65.                 RPC_BASE64 RPC_STRING $ENCODING $FORCE_STRING_ENCODING);
  66. %EXPORT_TAGS = (types => [ qw(RPC_BOOLEAN RPC_INT RPC_I4 RPC_DOUBLE RPC_STRING
  67.                               RPC_DATETIME_ISO8601 RPC_BASE64) ],
  68.                 all   => [ @EXPORT_OK ]);
  69.  
  70. $VERSION = '1.40';
  71.  
  72. # Global error string
  73. $ERROR = '';
  74.  
  75. # All of the RPC_* functions are convenience-encoders
  76. sub RPC_STRING           ( $ ) { RPC::XML::string->new($_[0]) }
  77. sub RPC_BOOLEAN          ( $ ) { RPC::XML::boolean->new($_[0]) }
  78. sub RPC_INT              ( $ ) { RPC::XML::int->new($_[0]) }
  79. sub RPC_I4               ( $ ) { RPC::XML::i4->new($_[0]) }
  80. sub RPC_DOUBLE           ( $ ) { RPC::XML::double->new($_[0]) }
  81. sub RPC_DATETIME_ISO8601 ( $ ) { RPC::XML::datetime_iso8601->new($_[0]) }
  82. sub RPC_BASE64           ( $ ) { RPC::XML::base64->new($_[0]) }
  83.  
  84. # This is a dead-simple ISO8601-from-UNIX-time stringifier. Always expresses
  85. # time in UTC.
  86. sub time2iso8601
  87. {
  88.     my $time = shift || time;
  89.     my $zone = shift || '';
  90.  
  91.     my @time = gmtime($time);
  92.     $time = sprintf("%4d%02d%02dT%02d:%02d:%02dZ",
  93.                     $time[5] + 1900, $time[4] + 1, @time[3, 2, 1, 0]);
  94.     if ($zone)
  95.     {
  96.         my $char = $zone > 0 ? '+' : '-';
  97.         chop $time; # Lose the Z if we're specifying a zone
  98.         $time .= $char . sprintf('%02d:00', abs($zone));
  99.     }
  100.  
  101.     $time;
  102. }
  103.  
  104. # This is a (futile?) attempt to provide a "smart" encoding method that will
  105. # take a Perl scalar and promote it to the appropriate RPC::XML::_type_.
  106. {
  107.     my $MaxInt      = 256**4;
  108.     my $MinInt      = $MaxInt * -1;
  109.  
  110.     my $MaxDouble   = 1e37;
  111.     my $MinDouble   = $MaxDouble * -1;
  112.  
  113.     sub smart_encode
  114.     {
  115.         my @values = @_;
  116.         my $type;
  117.  
  118.         @values = map
  119.         {
  120.             if (!defined $_)
  121.             {
  122.                 $type = RPC::XML::string->new('');
  123.             }
  124.             elsif (ref $_)
  125.             {
  126.                 # Skip any that have already been encoded
  127.                 if (UNIVERSAL::isa($_, 'RPC::XML::datatype'))
  128.                 {
  129.                     $type = $_;
  130.                 }
  131.                 elsif (UNIVERSAL::isa($_, 'HASH'))
  132.                 {
  133.                     $type = RPC::XML::struct->new($_);
  134.                 }
  135.                 elsif (UNIVERSAL::isa($_, 'ARRAY'))
  136.                 {
  137.                     $type = RPC::XML::array->new($_);
  138.                 }
  139.                 elsif (UNIVERSAL::isa($_, 'SCALAR'))
  140.                 {
  141.                     # This is a rare excursion into recursion, since the scalar
  142.                     # nature (de-refed from the object, so no longer magic)
  143.                     # will prevent further recursing.
  144.                     $type = smart_encode($$_);
  145.                 }
  146.                 else
  147.                 {
  148.                     # If the user passed in a reference that didn't pass one
  149.                     # of the above tests, we can't do anything with it:
  150.                     die "Un-convertable reference: $_, cannot use";
  151.                 }
  152.             }
  153.             # You have to check ints first, because they match the 
  154.             # next pattern too
  155.             # make sure not to encode digits that are larger than i4
  156.             elsif (! $FORCE_STRING_ENCODING and /^[-+]?\d+$/
  157.                    and $_ > $MinInt and $_ < $MaxInt)
  158.             {
  159.                 $type = RPC::XML::int->new($_);
  160.             }
  161.             # Pattern taken from perldata(1)
  162.             elsif (! $FORCE_STRING_ENCODING and
  163.                    /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/
  164.                    and $_ > $MinDouble and $_ < $MaxDouble)
  165.             {
  166.                 $type = RPC::XML::double->new($_);
  167.             }
  168.             else
  169.             {
  170.                 $type = RPC::XML::string->new($_);
  171.             }
  172.  
  173.             $type;
  174.         } @values;
  175.  
  176.         return (wantarray ? @values : $values[0]);
  177.     }
  178. }
  179.  
  180. # This is a (mostly) empty class used as a common superclass for simple and
  181. # complex types, so that their derivatives may be universally type-checked.
  182. package RPC::XML::datatype;
  183. use vars qw(@ISA);
  184. @ISA = ();
  185.  
  186. sub type { my $class = ref($_[0]) || $_[0]; $class =~ s/.*://; $class }
  187. sub is_fault { 0 }
  188.  
  189. ###############################################################################
  190. #
  191. #   Package:        RPC::XML::simple_type
  192. #
  193. #   Description:    A base class for the simpler type-classes to inherit from,
  194. #                   for default constructor, stringification, etc.
  195. #
  196. ###############################################################################
  197. package RPC::XML::simple_type;
  198.  
  199. use strict;
  200. use vars qw(@ISA);
  201.  
  202. @ISA = qw(RPC::XML::datatype);
  203.  
  204. # new - a generic constructor that presumes the value being stored is scalar
  205. sub new
  206. {
  207.     my $class = shift;
  208.     my $value = shift;
  209.  
  210.     $RPC::XML::ERROR = '';
  211.     $class = ref($class) || $class;
  212.     if (ref $value)
  213.     {
  214.         # If it is a scalar reference, just deref
  215.         if (UNIVERSAL::isa($value, 'SCALAR'))
  216.         {
  217.             $value = $$value;
  218.         }
  219.         else
  220.         {
  221.             # We can only manage scalar references (or blessed scalar refs)
  222.             $RPC::XML::ERROR = "${class}::new: Cannot instantiate from a " .
  223.                 'reference not derived from scalar';
  224.         }
  225.     }
  226.     bless \$value, $class;
  227. }
  228.  
  229. # value - a generic accessor
  230. sub value
  231. {
  232.     my $self = shift;
  233.  
  234.     $$self;
  235. }
  236.  
  237. # as_string - return the value as an XML snippet
  238. sub as_string
  239. {
  240.     my $self = shift;
  241.  
  242.     my $class;
  243.     return unless ($class = ref($self));
  244.     $class =~ s/^.*\://;
  245.     $class =~ s/_/./g;
  246.     substr($class, 0, 8) = 'dateTime' if (substr($class, 0, 8) eq 'datetime');
  247.  
  248.     "<$class>$$self</$class>";
  249. }
  250.  
  251. # Serialization for simple types is just a matter of sending as_string over
  252. sub serialize
  253. {
  254.     my ($self, $fh) = @_;
  255.  
  256.     print $fh $self->as_string;
  257. }
  258.  
  259. # The switch to serialization instead of in-memory strings means having to
  260. # calculate total size in bytes for Content-Length headers:
  261. sub length
  262. {
  263.     my $self = shift;
  264.  
  265.     length($self->as_string);
  266. }
  267.  
  268. ###############################################################################
  269. #
  270. #   Package:        RPC::XML::int
  271. #
  272. #   Description:    Data-type class for integers
  273. #
  274. ###############################################################################
  275. package RPC::XML::int;
  276.  
  277. use strict;
  278. use vars qw(@ISA);
  279.  
  280. @ISA = qw(RPC::XML::simple_type);
  281.  
  282. ###############################################################################
  283. #
  284. #   Package:        RPC::XML::i4
  285. #
  286. #   Description:    Data-type class for i4. Forces data into an int object.
  287. #
  288. ###############################################################################
  289. package RPC::XML::i4;
  290.  
  291. use strict;
  292. use vars qw(@ISA);
  293.  
  294. @ISA = qw(RPC::XML::simple_type);
  295.  
  296. ###############################################################################
  297. #
  298. #   Package:        RPC::XML::double
  299. #
  300. #   Description:    The "double" type-class
  301. #
  302. ###############################################################################
  303. package RPC::XML::double;
  304.  
  305. use strict;
  306. use vars qw(@ISA);
  307.  
  308. @ISA = qw(RPC::XML::simple_type);
  309.  
  310. sub as_string
  311. {
  312.     my $self = shift;
  313.  
  314.     return unless (my $class = ref($self));
  315.     $class =~ s/^.*\://;
  316.     (my $value = sprintf("%.20f", $$self)) =~ s/0+$//;
  317.  
  318.     "<$class>$value</$class>";
  319. }
  320.  
  321. ###############################################################################
  322. #
  323. #   Package:        RPC::XML::string
  324. #
  325. #   Description:    The "string" type-class
  326. #
  327. ###############################################################################
  328. package RPC::XML::string;
  329.  
  330. use strict;
  331. use vars qw(@ISA);
  332.  
  333. @ISA = qw(RPC::XML::simple_type);
  334.  
  335. # as_string - return the value as an XML snippet
  336. sub as_string
  337. {
  338.     my $self = shift;
  339.  
  340.     my ($class, $value);
  341.  
  342.     return unless ($class = $self->type);
  343.  
  344.     ($value = defined $$self ? $$self : '' )
  345.         =~ s/$RPC::XML::xmlre/$RPC::XML::xmlmap{$1}/ge;
  346.  
  347.     "<$class>$value</$class>";
  348. }
  349.  
  350. # Overloaded from simple_type, so that we can apply bytelength to the body
  351. sub length
  352. {
  353.     my $self = shift;
  354.  
  355.     RPC::XML::bytelength($self->as_string);
  356. }
  357.  
  358. ###############################################################################
  359. #
  360. #   Package:        RPC::XML::boolean
  361. #
  362. #   Description:    The type-class for boolean data. Handles some "extra" cases
  363. #
  364. ###############################################################################
  365. package RPC::XML::boolean;
  366.  
  367. use strict;
  368. use vars qw(@ISA);
  369.  
  370. @ISA = qw(RPC::XML::simple_type);
  371.  
  372. # This constructor allows any of true, false, yes or no to be specified
  373. sub new
  374. {
  375.     my $class = shift;
  376.     my $value = shift || 0;
  377.  
  378.     $RPC::XML::ERROR = '';
  379.     if ($value =~ /true|yes|1/i)
  380.     {
  381.         $value = 1;
  382.     }
  383.     elsif ($value =~ /false|no|0/i)
  384.     {
  385.         $value = 0;
  386.     }
  387.     else
  388.     {
  389.         $class = ref($class) || $class;
  390.         $RPC::XML::ERROR = "${class}::new: Value must be one of yes, no, " .
  391.             'true, false, 1, 0 (case-insensitive)';
  392.         return undef;
  393.     }
  394.  
  395.     bless \$value, $class;
  396. }
  397.  
  398. ###############################################################################
  399. #
  400. #   Package:        RPC::XML::datetime_iso8601
  401. #
  402. #   Description:    This is the class to manage ISO8601-style date/time values
  403. #
  404. ###############################################################################
  405. package RPC::XML::datetime_iso8601;
  406.  
  407. use strict;
  408. use vars qw(@ISA);
  409.  
  410. @ISA = qw(RPC::XML::simple_type);
  411.  
  412. sub type { 'dateTime.iso8601' };
  413.  
  414. ###############################################################################
  415. #
  416. #   Package:        RPC::XML::array
  417. #
  418. #   Description:    This class encapsulates the array data type. Each element
  419. #                   within the array should be one of the datatype classes.
  420. #
  421. ###############################################################################
  422. package RPC::XML::array;
  423.  
  424. use strict;
  425. use vars qw(@ISA);
  426.  
  427. @ISA = qw(RPC::XML::datatype);
  428.  
  429. # The constructor for this class mainly needs to sanity-check the value data
  430. sub new
  431. {
  432.     my $class = shift;
  433.     my @args = (UNIVERSAL::isa($_[0], 'ARRAY')) ? @{$_[0]} : @_;
  434.  
  435.     # First ensure that each argument passed in is itself one of the data-type
  436.     # class instances.
  437.     for (@args)
  438.     {
  439.         $_ = RPC::XML::smart_encode($_)
  440.             unless (UNIVERSAL::isa($_, 'RPC::XML::datatype'));
  441.     }
  442.  
  443.     bless \@args, $class;
  444. }
  445.  
  446. # This became more complex once it was shown that there may be a need to fetch
  447. # the value while preserving the underlying objects.
  448. sub value
  449. {
  450.     my $self = shift;
  451.     my $no_recurse = shift || 0;
  452.     my $ret;
  453.  
  454.     if ($no_recurse)
  455.     {
  456.         $ret = [ @$self ];
  457.     }
  458.     else
  459.     {
  460.         $ret = [ map { $_->value } @$self ];
  461.     }
  462.  
  463.     $ret;
  464. }
  465.  
  466. sub as_string
  467. {
  468.     my $self = shift;
  469.  
  470.     join('',
  471.          '<array><data>',
  472.          (map { ('<value>', $_->as_string(), '</value>') } (@$self)),
  473.          '</data></array>');
  474. }
  475.  
  476. # Serialization for arrays is not as straight-forward as it is for simple
  477. # types. One or more of the elements may be a base64 object, which has a
  478. # non-trivial serialize() method. Thus, rather than just sending the data from
  479. # as_string down the pipe, instead call serialize() recursively on all of the
  480. # elements.
  481. sub serialize
  482. {
  483.     my ($self, $fh) = @_;
  484.  
  485.     print $fh '<array><data>';
  486.     for (@$self)
  487.     {
  488.         print $fh '<value>';
  489.         $_->serialize($fh);
  490.         print $fh '</value>';
  491.     }
  492.     print $fh '</data></array>';
  493. }
  494.  
  495. # Length calculation starts to get messy here, due to recursion
  496. sub length
  497. {
  498.     my $self = shift;
  499.  
  500.     # Start with the constant components in the text
  501.     my $len = 28; # That the <array><data></data></array> part
  502.     for (@$self) { $len += (15 + $_->length) } # 15 is for <value></value>
  503.  
  504.     $len;
  505. }
  506.  
  507. ###############################################################################
  508. #
  509. #   Package:        RPC::XML::struct
  510. #
  511. #   Description:    This is the "struct" data class. The struct is like Perl's
  512. #                   hash, with the constraint that all values are instances
  513. #                   of the datatype classes.
  514. #
  515. ###############################################################################
  516. package RPC::XML::struct;
  517.  
  518. use strict;
  519. use vars qw(@ISA);
  520.  
  521. @ISA = qw(RPC::XML::datatype);
  522.  
  523. # The constructor for this class mainly needs to sanity-check the value data
  524. sub new
  525. {
  526.     my $class = shift;
  527.     my %args = (UNIVERSAL::isa($_[0], 'HASH')) ? %{$_[0]} : @_;
  528.  
  529.     # First ensure that each argument passed in is itself one of the data-type
  530.     # class instances.
  531.     for (keys %args)
  532.     {
  533.         $args{$_} = RPC::XML::smart_encode($args{$_})
  534.             unless (UNIVERSAL::isa($args{$_}, 'RPC::XML::datatype'));
  535.     }
  536.  
  537.     bless \%args, $class;
  538. }
  539.  
  540. # This became more complex once it was shown that there may be a need to fetch
  541. # the value while preserving the underlying objects.
  542. sub value
  543. {
  544.     my $self = shift;
  545.     my $no_recurse = shift || 0;
  546.     my %value;
  547.  
  548.     if ($no_recurse)
  549.     {
  550.         %value = map { $_, $self->{$_} } (keys %$self);
  551.     }
  552.     else
  553.     {
  554.         %value = map { $_, $self->{$_}->value } (keys %$self);
  555.     }
  556.  
  557.     \%value;
  558. }
  559.  
  560. sub as_string
  561. {
  562.     my $self = shift;
  563.     my $key;
  564.  
  565.     join('',
  566.          '<struct>',
  567.          (map {
  568.              ($key = $_) =~ s/$RPC::XML::xmlre/$RPC::XML::xmlmap{$1}/ge;
  569.              ("<member><name>$key</name><value>",
  570.               $self->{$_}->as_string,
  571.               '</value></member>')
  572.          } (keys %$self)),
  573.          '</struct>');
  574. }
  575.  
  576. # As with the array type, serialization here isn't cut and dried, since one or
  577. # more values may be base64.
  578. sub serialize
  579. {
  580.     my ($self, $fh) = @_;
  581.     my $key;
  582.  
  583.     print $fh '<struct>';
  584.     for (keys %$self)
  585.     {
  586.         ($key = $_) =~ s/$RPC::XML::xmlre/$RPC::XML::xmlmap{$1}/ge;
  587.         print $fh "<member><name>$key</name><value>";
  588.         $self->{$_}->serialize($fh);
  589.         print $fh '</value></member>';
  590.     }
  591.     print $fh '</struct>';
  592. }
  593.  
  594. # Length calculation is a real pain here. But not as bad as base64 promises
  595. sub length
  596. {
  597.     my $self = shift;
  598.  
  599.     my $len = 17; # <struct></struct>
  600.     for (keys %$self)
  601.     {
  602.         $len += 45; # For all the constant XML presence
  603.         $len += length($_);
  604.         $len += $self->{$_}->length;
  605.     }
  606.  
  607.     $len;
  608. }
  609.  
  610. ###############################################################################
  611. #
  612. #   Package:        RPC::XML::base64
  613. #
  614. #   Description:    This is the base64-encoding type. Plain data is passed in,
  615. #                   plain data is returned. Plain is always returned. All the
  616. #                   encoding/decoding is done behind the scenes.
  617. #
  618. ###############################################################################
  619. package RPC::XML::base64;
  620.  
  621. use strict;
  622. use vars qw(@ISA);
  623.  
  624. @ISA = qw(RPC::XML::datatype);
  625.  
  626. sub new
  627. {
  628.     require MIME::Base64;
  629.     my ($class, $value, $encoded) = @_;
  630.  
  631.     my $self = {};
  632.  
  633.     $RPC::XML::ERROR = '';
  634.  
  635.     $self->{encoded} = $encoded ? 1 : 0; # Is this already Base-64?
  636.     $self->{inmem}   = 0;                # To signal in-memory vs. filehandle
  637.  
  638.     # First, determine if the call sent actual data, a reference to actual
  639.     # data, or an open filehandle.
  640.     if (ref($value) and UNIVERSAL::isa($value, 'GLOB'))
  641.     {
  642.         # This is a seekable filehandle (or acceptable substitute thereof).
  643.         # This assignment increments the ref-count, and prevents destruction
  644.         # in other scopes.
  645.         binmode $value;
  646.         $self->{value_fh} = $value;
  647.         $self->{fh_pos}   = tell($value);
  648.     }
  649.     else
  650.     {
  651.         # Not a filehandle. Might be a scalar ref, but other than that it's
  652.         # in-memory data.
  653.         $self->{inmem}++;
  654.         $self->{value} = ref($value) ? $$value : $value;
  655.         unless (defined $value and length $value)
  656.         {
  657.             $class = ref($class) || $class;
  658.             $RPC::XML::ERROR = "${class}::new: Must be called with non-null " .
  659.                 'data or an open, seekable filehandle';
  660.             return undef;
  661.         }
  662.         # We want in-memory data to always be in the clear, to reduce the tests
  663.         # needed in value(), below.
  664.         if ($self->{encoded})
  665.         {
  666.             local($^W) = 0; # Disable warnings in case the data is underpadded
  667.             $self->{value} = MIME::Base64::decode_base64($self->{value});
  668.             $self->{encoded} = 0;
  669.         }
  670.     }
  671.  
  672.     bless $self, $class;
  673. }
  674.  
  675. sub value
  676. {
  677.     my $self      = shift;
  678.     my $as_base64 = (defined $_[0] and $_[0]) ? 1 : 0;
  679.  
  680.     # There are six cases here, based on whether or not the data exists in
  681.     # Base-64 or clear form, and whether the data is in-memory or needs to be
  682.     # read from a filehandle.
  683.     if ($self->{inmem})
  684.     {
  685.         # This is simplified into two cases (rather than four) since we always
  686.         # keep in-memory data as cleartext
  687.         return $as_base64 ?
  688.             MIME::Base64::encode_base64($self->{value}, '') : $self->{value};
  689.     }
  690.     else
  691.     {
  692.         # This is trickier with filehandle-based data, since we chose not to
  693.         # change the state of the data. Thus, the behavior is dependant not
  694.         # only on $as_base64, but also on $self->{encoded}. This is why we
  695.         # took pains to explicitly set $as_base64 to either 0 or 1, rather than
  696.         # just accept whatever non-false value the caller sent. It makes this
  697.         # first test possible.
  698.         my ($accum, $pos, $res);
  699.         $accum = '';
  700.  
  701.         $self->{fh_pos} = tell($self->{value_fh});
  702.         seek($self->{value_fh}, 0, 0);
  703.         if ($as_base64 == $self->{encoded})
  704.         {
  705.             $pos = 0;
  706.             while ($res = read($self->{value_fh}, $accum, 1024, $pos))
  707.             {
  708.                 $pos += $res;
  709.             }
  710.         }
  711.         else
  712.         {
  713.             if ($as_base64)
  714.             {
  715.                 # We're reading cleartext and converting it to Base-64. Read in
  716.                 # multiples of 57 bytes for best Base-64 calculation. The
  717.                 # choice of 60 for the multiple is purely arbitrary.
  718.                 $res = '';
  719.                 while (read($self->{value_fh}, $res, 60*57))
  720.                 {
  721.                     $accum .= MIME::Base64::encode_base64($res, '');
  722.                 }
  723.             }
  724.             else
  725.             {
  726.                 # Reading Base-64 and converting it back to cleartext. If the
  727.                 # Base-64 data doesn't have any line-breaks, no telling how
  728.                 # much memory this will eat up.
  729.                 local($^W) = 0; # Disable padding-length warnings
  730.                 $pos = $self->{value_fh};
  731.                 while (defined($res = <$pos>))
  732.                 {
  733.                     $accum .= MIME::Base64::decode_base64($res);
  734.                 }
  735.             }
  736.         }
  737.         seek($self->{value_fh}, $self->{fh_pos}, 0);
  738.  
  739.         return $accum;
  740.     }
  741. }
  742.  
  743. # The value needs to be encoded before being output
  744. sub as_string
  745. {
  746.     my $self = shift;
  747.  
  748.     '<base64>' . $self->value('encoded') . '</base64>';
  749. }
  750.  
  751. # If it weren't for Tellme and their damnable WAV files, and ViAir and their
  752. # half-baked XML-RPC server, I wouldn't have to do any of this...
  753. sub serialize
  754. {
  755.     my ($self, $fh) = @_;
  756.  
  757.     # If the data is in-memory, just call as_string and pass it down the pipe
  758.     if ($self->{inmem})
  759.     {
  760.         print $fh $self->as_string;
  761.     }
  762.     else
  763.     {
  764.         # If it's a filehandle, at least we take comfort in knowing that we
  765.         # always want Base-64 at this level.
  766.         my $buf = '';
  767.         $self->{fh_pos} = tell($self->{value_fh});
  768.         seek($self->{value_fh}, 0, 0);
  769.         print $fh '<base64>';
  770.         if ($self->{encoded})
  771.         {
  772.             # Easy-- just use read() to send it down in palatably-sized chunks
  773.             while (read($self->{value_fh}, $buf, 4096))
  774.             {
  775.                 print $fh $buf;
  776.             }
  777.         }
  778.         else
  779.         {
  780.             # This actually requires work. As with value(), the 60*57 is based
  781.             # on ideal Base-64 chunks, with the 60 part being arbitrary.
  782.             while (read($self->{value_fh}, $buf, 60*57))
  783.             {
  784.                 print $fh &MIME::Base64::encode_base64($buf, '');
  785.             }
  786.         }
  787.         print $fh '</base64>';
  788.         seek($self->{value_fh}, $self->{fh_pos}, 0);
  789.     }
  790. }
  791.  
  792. # This promises to be a big enough pain that I seriously considered opening
  793. # an anon-temp file (one that's unlinked for security, and survives only as
  794. # long as the FH is open) and passing that to serialize just to -s on the FH.
  795. # But I'll do this the "right" way instead...
  796. sub length
  797. {
  798.     my $self = shift;
  799.  
  800.     # Start with the constant bits
  801.     my $len = 17; # <base64></base64>
  802.  
  803.     if ($self->{inmem})
  804.     {
  805.         # If it's in-memory, it's cleartext. Size the encoded version
  806.         $len += length(MIME::Base64::encode_base64($self->{value}, ''));
  807.     }
  808.     else
  809.     {
  810.         if ($self->{encoded})
  811.         {
  812.             # We're lucky, it's already encoded in the file, and -s will do
  813.             $len += -s $self->{value_fh};
  814.         }
  815.         else
  816.         {
  817.             # Oh bugger. We have to encode it.
  818.             my $buf = '';
  819.             my $cnt = 0;
  820.  
  821.             $self->{fh_pos} = tell($self->{value_fh});
  822.             seek($self->{value_fh}, 0, 0);
  823.             while ($cnt = read($self->{value_fh}, $buf, 60*57))
  824.             {
  825.                 $len += length(MIME::Base64::encode_base64($buf, ''));
  826.             }
  827.             seek($self->{value_fh}, $self->{fh_pos}, 0);
  828.         }
  829.     }
  830.  
  831.     $len;
  832. }
  833.  
  834. # This allows writing the decoded data to an arbitrary file. It's useful when
  835. # an application has gotten a RPC::XML::base64 object back from a request, and
  836. # knows that it needs to go straight to a file without being completely read
  837. # into memory, first.
  838. sub to_file
  839. {
  840.     my ($self, $file) = @_;
  841.  
  842.     my ($fh, $buf, $do_close, $count) = (undef, '', 0, 0);
  843.  
  844.     if (ref $file and UNIVERSAL::isa($file, 'GLOB'))
  845.     {
  846.         $fh = $file;
  847.     }
  848.     else
  849.     {
  850.         require Symbol;
  851.         $fh = Symbol::gensym();
  852.         unless (open($fh, "> $file"))
  853.         {
  854.             $RPC::XML::ERROR = $!;
  855.             return -1;
  856.         }
  857.         binmode $fh;
  858.         $do_close++;
  859.     }
  860.  
  861.     # If all the data is in-memory, then we know that it's clear, and we
  862.     # don't have to jump through hoops in moving it to the filehandle.
  863.     if ($self->{inmem})
  864.     {
  865.         print $fh $self->{value};
  866.         $count = CORE::length($self->{value});
  867.     }
  868.     else
  869.     {
  870.         # Filehandle-to-filehandle transfer.
  871.  
  872.         # Now determine if the data can be copied over directly, or if we have
  873.         # to decode it along the way.
  874.         $self->{fh_pos} = tell($self->{value_fh});
  875.         seek($self->{value_fh}, 0, 0);
  876.         if ($self->{encoded})
  877.         {
  878.             # As with the caveat in value(), if the base-64 data doesn't have
  879.             # any line-breaks, no telling how much memory this will eat up.
  880.             local($^W) = 0; # Disable padding-length warnings
  881.             my $tmp_fh = $self->{value_fh};
  882.             while (defined($_ = <$tmp_fh>))
  883.             {
  884.                 $buf = MIME::Base64::decode_base64($_);
  885.                 print $fh $buf;
  886.                 $count += CORE::length($buf);
  887.             }
  888.         }
  889.         else
  890.         {
  891.             my $size;
  892.             while ($size = read($self->{value_fh}, $buf, 4096))
  893.             {
  894.                 print $fh $buf;
  895.                 $count += $size;
  896.             }
  897.         }
  898.         seek($self->{value_fh}, $self->{fh_pos}, 0);
  899.     }
  900.  
  901.     close($fh) if $do_close;
  902.     return $count;
  903. }
  904.  
  905. ###############################################################################
  906. #
  907. #   Package:        RPC::XML::fault
  908. #
  909. #   Description:    This is the class that encapsulates the data for a RPC
  910. #                   fault-response. Like the others, it takes the relevant
  911. #                   information and maintains it internally. This is put
  912. #                   at the end of the datum types, though it isn't really a
  913. #                   data type in the sense that it cannot be passed in to a
  914. #                   request. But it is separated so as to better generalize
  915. #                   responses.
  916. #
  917. ###############################################################################
  918. package RPC::XML::fault;
  919.  
  920. use strict;
  921. use vars qw(@ISA);
  922.  
  923. @ISA = qw(RPC::XML::struct);
  924.  
  925. # For our new(), we only need to ensure that we have the two required members
  926. sub new
  927. {
  928.     my $class = shift;
  929.     my @args = @_;
  930.  
  931.     my ($self, %args);
  932.  
  933.     $RPC::XML::ERROR = '';
  934.     if (ref($args[0]) and UNIVERSAL::isa($args[0], 'RPC::XML::struct'))
  935.     {
  936.         # Take the keys and values from the struct object as our own
  937.         %args = %{$args[0]->value('shallow')};
  938.     }
  939.     elsif (@args == 2)
  940.     {
  941.         # This is a special convenience-case to make simple new() calls clearer
  942.         %args = (faultCode   => RPC::XML::int->new($args[0]),
  943.                  faultString => RPC::XML::string->new($args[1]));
  944.     }
  945.     else
  946.     {
  947.         %args = @args;
  948.     }
  949.  
  950.     unless ($args{faultCode} and $args{faultString})
  951.     {
  952.         $class = ref($class) || $class;
  953.         $RPC::XML::ERROR = "${class}::new: Missing required struct fields";
  954.         return undef;
  955.     }
  956.     if (scalar(keys %args) > 2)
  957.     {
  958.         $class = ref($class) || $class;
  959.         $RPC::XML::ERROR = "${class}::new: Extra struct fields not allowed";
  960.         return undef;
  961.     }
  962.  
  963.     $self = $class->SUPER::new(%args);
  964. }
  965.  
  966. # This only differs from the display of a struct in that it has some extra
  967. # wrapped around it. Let the superclass as_string method do most of the work.
  968. sub as_string
  969. {
  970.     my $self = shift;
  971.  
  972.     '<fault><value>' . $self->SUPER::as_string . '</value></fault>';
  973. }
  974.  
  975. # Because of the slight diff above, length() has to be different from struct
  976. sub length
  977. {
  978.     my $self = shift;
  979.  
  980.     my $len = 30; # Constant XML content
  981.     $len += $self->SUPER::length;
  982.  
  983.     $len;
  984. }
  985.  
  986. # Convenience methods:
  987. sub code   { $_[0]->{faultCode}->value   }
  988. sub string { $_[0]->{faultString}->value }
  989.  
  990. # This is the only one to override this method, for obvious reasons
  991. sub is_fault { 1 }
  992.  
  993. ###############################################################################
  994. #
  995. #   Package:        RPC::XML::request
  996. #
  997. #   Description:    This is the class that encapsulates the data for a RPC
  998. #                   request. It takes the relevant information and maintains
  999. #                   it internally until asked to stringify. Only then is the
  1000. #                   XML generated, encoding checked, etc. This allows for
  1001. #                   late-selection of <methodCall> or <methodCallSet> as a
  1002. #                   containing tag.
  1003. #
  1004. #                   This class really only needs a constructor and a method
  1005. #                   to stringify.
  1006. #
  1007. ###############################################################################
  1008. package RPC::XML::request;
  1009.  
  1010. use strict;
  1011. use vars qw(@ISA);
  1012.  
  1013. ###############################################################################
  1014. #
  1015. #   Sub Name:       new
  1016. #
  1017. #   Description:    Creating a new request object, in this (reference) case,
  1018. #                   means checking the list of arguments for sanity and
  1019. #                   packaging it up for later use.
  1020. #
  1021. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1022. #                   $class    in      scalar    Class/ref to bless into
  1023. #                   @argz     in      list      The exact disposition of the
  1024. #                                                 arguments is based on the
  1025. #                                                 type of the various elements
  1026. #
  1027. #   Returns:        Success:    object ref
  1028. #                   Failure:    undef, error in $RPC::XML::ERROR
  1029. #
  1030. ###############################################################################
  1031. sub new
  1032. {
  1033.     my $class = shift;
  1034.     my @argz = @_;
  1035.  
  1036.     my ($self, $name);
  1037.  
  1038.     $class = ref($class) || $class;
  1039.     $RPC::XML::ERROR = '';
  1040.  
  1041.     unless (@argz)
  1042.     {
  1043.         $RPC::XML::ERROR = 'RPC::XML::request::new: At least a method name ' .
  1044.             'must be specified';
  1045.         return undef;
  1046.     }
  1047.  
  1048.     if (UNIVERSAL::isa($argz[0], 'RPC::XML::request'))
  1049.     {
  1050.         # Maybe this will be a clone operation
  1051.     }
  1052.     else
  1053.     {
  1054.         # This is the method name to be called
  1055.         $name = shift(@argz);
  1056.         # All the remaining args must be data.
  1057.         @argz = RPC::XML::smart_encode(@argz);
  1058.         $self = { args => [ @argz ], name => $name };
  1059.         bless $self, $class;
  1060.     }
  1061.  
  1062.     $self;
  1063. }
  1064.  
  1065. # Accessor methods
  1066. sub name       { shift->{name}       }
  1067. sub args       { shift->{args} || [] }
  1068.  
  1069. ###############################################################################
  1070. #
  1071. #   Sub Name:       as_string
  1072. #
  1073. #   Description:    This is a fair bit more complex than the simple as_string
  1074. #                   methods for the datatypes. Express the invoking object as
  1075. #                   a well-formed XML document.
  1076. #
  1077. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1078. #                   $self     in      ref       Invoking object
  1079. #                   $indent   in      scalar    Indention level for output
  1080. #
  1081. #   Returns:        Success:    text
  1082. #                   Failure:    undef
  1083. #
  1084. ###############################################################################
  1085. sub as_string
  1086. {
  1087.     my $self   = shift;
  1088.  
  1089.     my $text;
  1090.  
  1091.     $RPC::XML::ERROR = '';
  1092.  
  1093.     $text = qq(<?xml version="1.0" encoding="$RPC::XML::ENCODING"?>);
  1094.  
  1095.     $text .= "<methodCall><methodName>$self->{name}</methodName><params>";
  1096.     for (@{$self->{args}})
  1097.     {
  1098.         $text .= '<param><value>' . $_->as_string . '</value></param>';
  1099.     }
  1100.     $text .= '</params></methodCall>';
  1101.  
  1102.     $text;
  1103. }
  1104.  
  1105. # The difference between stringifying and serializing a request is much like
  1106. # the difference was for structs and arrays. The boilerplate is the same, but
  1107. # the destination is different in a sensitive way.
  1108. sub serialize
  1109. {
  1110.     my ($self, $fh) = @_;
  1111.  
  1112.     print $fh qq(<?xml version="1.0" encoding="$RPC::XML::ENCODING"?>);
  1113.  
  1114.     print $fh "<methodCall><methodName>$self->{name}</methodName><params>";
  1115.     for (@{$self->{args}})
  1116.     {
  1117.         print $fh '<param><value>';
  1118.         $_->serialize($fh);
  1119.         print $fh '</value></param>';
  1120.     }
  1121.     print $fh '</params></methodCall>';
  1122. }
  1123.  
  1124. # Compared to base64, length-calculation here is pretty easy, much like struct
  1125. sub length
  1126. {
  1127.     my $self = shift;
  1128.  
  1129.     my $len = 100 + length($RPC::XML::ENCODING); # All the constant XML present
  1130.     $len += length($self->{name});
  1131.  
  1132.     for (@{$self->{args}})
  1133.     {
  1134.         $len += 30; # Constant XML
  1135.         $len += $_->length;
  1136.     }
  1137.  
  1138.     $len;
  1139. }
  1140.  
  1141. ###############################################################################
  1142. #
  1143. #   Package:        RPC::XML::response
  1144. #
  1145. #   Description:    This is the class that encapsulates the data for a RPC
  1146. #                   response. As above, it takes the information and maintains
  1147. #                   it internally until asked to stringify. Only then is the
  1148. #                   XML generated, encoding checked, etc. This allows for
  1149. #                   late-selection of <methodResponse> or <methodResponseSet>
  1150. #                   as above.
  1151. #
  1152. ###############################################################################
  1153. package RPC::XML::response;
  1154.  
  1155. use strict;
  1156. use vars qw(@ISA);
  1157.  
  1158. ###############################################################################
  1159. #
  1160. #   Sub Name:       new
  1161. #
  1162. #   Description:    Creating a new response object, in this (reference) case,
  1163. #                   means checking the outgoing parameter(s) for sanity.
  1164. #
  1165. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1166. #                   $class    in      scalar    Class/ref to bless into
  1167. #                   @argz     in      list      The exact disposition of the
  1168. #                                                 arguments is based on the
  1169. #                                                 type of the various elements
  1170. #
  1171. #   Returns:        Success:    object ref
  1172. #                   Failure:    undef, error in $RPC::XML::ERROR
  1173. #
  1174. ###############################################################################
  1175. sub new
  1176. {
  1177.     my $class = shift;
  1178.     my @argz = @_;
  1179.  
  1180.     my ($self, %extra, %attr);
  1181.  
  1182.     $class = ref($class) || $class;
  1183.  
  1184.     $RPC::XML::ERROR = '';
  1185.     if (! @argz)
  1186.     {
  1187.         $RPC::XML::ERROR = 'RPC::XML::response::new: One of a datatype, ' .
  1188.             'value or a fault object must be specified';
  1189.     }
  1190.     elsif (UNIVERSAL::isa($argz[0], 'RPC::XML::response'))
  1191.     {
  1192.         # This will eventually be a clone-operation. For now, just return in
  1193.         $self = $argz[0];
  1194.     }
  1195.     elsif (@argz > 1)
  1196.     {
  1197.         $RPC::XML::ERROR = 'RPC::XML::response::new: Responses may take ' .
  1198.             'only one argument';
  1199.     }
  1200.     else
  1201.     {
  1202.         $argz[0] = RPC::XML::smart_encode($argz[0]);
  1203.  
  1204.         $self = { value => $argz[0] };
  1205.         bless $self, $class;
  1206.     }
  1207.  
  1208.     $self;
  1209. }
  1210.  
  1211. # Accessor/status methods
  1212. sub value      { $_[0]->{value} }
  1213. sub is_fault   { $_[0]->{value}->is_fault }
  1214.  
  1215. ###############################################################################
  1216. #
  1217. #   Sub Name:       as_string
  1218. #
  1219. #   Description:    This is a fair bit more complex than the simple as_string
  1220. #                   methods for the datatypes. Express the invoking object as
  1221. #                   a well-formed XML document.
  1222. #
  1223. #   Arguments:      NAME      IN/OUT  TYPE      DESCRIPTION
  1224. #                   $self     in      ref       Invoking object
  1225. #                   $indent   in      scalar    Indention level for output
  1226. #
  1227. #   Returns:        Success:    text
  1228. #                   Failure:    undef
  1229. #
  1230. ###############################################################################
  1231. sub as_string
  1232. {
  1233.     my $self   = shift;
  1234.  
  1235.     my $text;
  1236.  
  1237.     $RPC::XML::ERROR = '';
  1238.  
  1239.     $text = qq(<?xml version="1.0" encoding="$RPC::XML::ENCODING"?>);
  1240.  
  1241.     $text .= '<methodResponse>';
  1242.     if ($self->{value}->isa('RPC::XML::fault'))
  1243.     {
  1244.         $text .= $self->{value}->as_string;
  1245.     }
  1246.     else
  1247.     {
  1248.         $text .= '<params><param><value>' . $self->{value}->as_string .
  1249.             '</value></param></params>';
  1250.     }
  1251.     $text .= '</methodResponse>';
  1252.  
  1253.     $text;
  1254. }
  1255.  
  1256. # See the comment for serialize() above in RPC::XML::request
  1257. sub serialize
  1258. {
  1259.     my ($self, $fh) = @_;
  1260.  
  1261.     print $fh qq(<?xml version="1.0" encoding="$RPC::XML::ENCODING"?>);
  1262.  
  1263.     print $fh '<methodResponse>';
  1264.     if ($self->{value}->isa('RPC::XML::fault'))
  1265.     {
  1266.         # This also bypasses a un-needed call to serialize in the struct
  1267.         # package, since we know by definition that there is no base64 data
  1268.         # in a fault.
  1269.         print $fh $self->{value}->as_string;
  1270.     }
  1271.     else
  1272.     {
  1273.         print $fh '<params><param><value>';
  1274.         $self->{value}->serialize($fh);
  1275.         print $fh '</value></param></params>';
  1276.     }
  1277.     print $fh '</methodResponse>';
  1278. }
  1279.  
  1280. # Compared to base64, length-calculation here is pretty easy, much like struct
  1281. sub length
  1282. {
  1283.     my $self = shift;
  1284.  
  1285.     my $len = 66 + length($RPC::XML::ENCODING); # All the constant XML present
  1286.  
  1287.     # This boilerplate XML is only present when it is NOT a fault
  1288.     $len += 47 unless ($self->{value}->isa('RPC::XML::fault'));
  1289.     $len += $self->{value}->length;
  1290.  
  1291.     $len;
  1292. }
  1293.  
  1294. 1;
  1295.  
  1296. __END__
  1297.  
  1298. =head1 NAME
  1299.  
  1300. RPC::XML - A set of classes for core data, message and XML handling
  1301.  
  1302. =head1 SYNOPSIS
  1303.  
  1304.     use RPC::XML;
  1305.  
  1306.     $req = RPC::XML::request->new('fetch_prime_factors',
  1307.                                   RPC::XML::int->new(985120528));
  1308.     ...
  1309.     $resp = RPC::XML::Parser->new()->parse(STREAM);
  1310.     if (ref($resp))
  1311.     {
  1312.         return $resp->value->value;
  1313.     }
  1314.     else
  1315.     {
  1316.         die $resp;
  1317.     }
  1318.  
  1319. =head1 DESCRIPTION
  1320.  
  1321. The B<RPC::XML> package is an implementation of the B<XML-RPC> standard.
  1322.  
  1323. The package provides a set of classes for creating values to pass to the
  1324. constructors for requests and responses. These are lightweight objects, most
  1325. of which are implemented as tied scalars so as to associate specific type
  1326. information with the value. Classes are also provided for requests, responses,
  1327. faults (errors) and a parser based on the L<XML::Parser> package from CPAN.
  1328.  
  1329. This module does not actually provide any transport implementation or
  1330. server basis. For these, see L<RPC::XML::Client> and L<RPC::XML::Server>,
  1331. respectively.
  1332.  
  1333. =head1 EXPORTABLE FUNCTIONS
  1334.  
  1335. At present, three simple functions are available for import. They must be
  1336. explicitly imported as part of the C<use> statement, or with a direct call to
  1337. C<import>:
  1338.  
  1339. =over 4
  1340.  
  1341. =item time2iso8601([$time])
  1342.  
  1343. Convert the integer time value in C<$time> (which defaults to calling the
  1344. built-in C<time> if not present) to a ISO 8601 string in the UTC time
  1345. zone. This is a convenience function for occassions when the return value
  1346. needs to be of the B<dateTime.iso8601> type, but the value on hand is the
  1347. return from the C<time> built-in.
  1348.  
  1349. =item smart_encode(@args)
  1350.  
  1351. Converts the passed-in arguments to datatype objects. Any that are already
  1352. encoded as such are passed through unchanged. The routine is called recursively
  1353. on hash and array references. Note that this routine can only deduce a certain
  1354. degree of detail about the values passed. Boolean values will be wrongly
  1355. encoded as integers. Pretty much anything not specifically recognizable will
  1356. get encoded as a string object. Thus, for types such as C<fault>, the ISO
  1357. time value, base-64 data, etc., the program must still explicitly encode it.
  1358. However, this routine will hopefully simplify things a little bit for a
  1359. majority of the usage cases.
  1360.  
  1361. =item bytelength([$string])
  1362.  
  1363. Returns the length of the string passed in, in bytes rather than characters.
  1364. In Perl prior to 5.6.0 when there was little or no Unicode support, this has
  1365. no difference from the C<length> function. if the B<bytes> pragme is
  1366. available, then the length measured is raw bytes, even when faced with
  1367. multi-byte characters. If no argument is passed in, operates on C<$_>.
  1368.  
  1369. =back
  1370.  
  1371. In addition to these three, the following "helper" functions are also
  1372. available. They may be imported explicitly, or via a tag of C<:types>:
  1373.  
  1374.     RPC_BOOLEAN RPC_INT RPC_I4 RPC_DOUBLE RPC_DATETIME_ISO8601
  1375.     RPC_BASE64 RPC_STRING
  1376.  
  1377. Each creates a data object of the appropriate type from a single value. They
  1378. are merely short-hand for calling the constructors of the data classes
  1379. directly.
  1380.  
  1381. All of the above (helpers and the first three functions) may be imported via
  1382. the tag C<:all>.
  1383.  
  1384. =head1 CLASSES
  1385.  
  1386. The classes provided by this module are broken into two groups: I<datatype>
  1387. classes and I<message> classes.
  1388.  
  1389. =head2 Data Classes
  1390.  
  1391. The following data classes are provided by this library. Each of these provide
  1392. at least the set of methods below. Note that these classes are designed to
  1393. create throw-away objects. There is currently no mechanism for changing the
  1394. value stored within one of these object after the constructor returns. It is
  1395. assumed that a new object would be created, instead.
  1396.  
  1397. The common methods to all data classes are:
  1398.  
  1399. =over 4
  1400.  
  1401. =item new($value)
  1402.  
  1403. Constructor. The value passed in is the value to be encapsulated in the new
  1404. object.
  1405.  
  1406. =item value
  1407.  
  1408. Returns the value kept in the object. Processes recursively for C<array> and
  1409. C<struct> objects.
  1410.  
  1411. =item as_string
  1412.  
  1413. Returns the value as a XML-RPC fragment, with the proper tags, etc.
  1414.  
  1415. =item serialize($filehandle)
  1416.  
  1417. Send the stringified rendition of the data to the given file handle. This
  1418. allows messages with arbitrarily-large Base-64 data within them to be sent
  1419. without having to hold the entire message within process memory.
  1420.  
  1421. =item length
  1422.  
  1423. Returns the length, in bytes, of the object when serialized into XML. This is
  1424. used by the client and server classes to calculate message length.
  1425.  
  1426. =item type
  1427.  
  1428. Returns the type of data being stored in an object. The type matches the
  1429. XML-RPC specification, so the normalized form C<datetime_iso8601> comes back
  1430. as C<dateTime.iso8601>.
  1431.  
  1432. =item is_fault
  1433.  
  1434. All types except the fault class return false for this. This is to allow
  1435. consistent testing of return values for fault status, without checking for a
  1436. hash reference with specific keys defined.
  1437.  
  1438. =back
  1439.  
  1440. The classes themselves are:
  1441.  
  1442. =over 4
  1443.  
  1444. =item RPC::XML::int
  1445.  
  1446. Creates an integer value. Constructor expects the integer value as an
  1447. argument.
  1448.  
  1449. =item RPC::XML::i4
  1450.  
  1451. This is like the C<int> class. Note that services written in strictly-typed
  1452. languages such as C, C++ or Java may consider the C<i4> and C<int> types as
  1453. distinct and different.
  1454.  
  1455. =item RPC::XML::double
  1456.  
  1457. Creates a floating-point value.
  1458.  
  1459. =item RPC::XML::string
  1460.  
  1461. Creates an arbitrary string. No special encoding is done to the string (aside
  1462. from XML document encoding, covered later) with the exception of the C<E<lt>>,
  1463. C<E<gt>> and C<&> characters, which are XML-escaped during object creation,
  1464. and then reverted when the C<value> method is called.
  1465.  
  1466. =item RPC::XML::boolean
  1467.  
  1468. Creates a boolean value. The value returned will always be either of B<1>
  1469. or B<0>, for true or false, respectively. When calling the constructor, the
  1470. program may specify any of: C<0>, C<no>, C<false>, C<1>, C<yes>, C<true>.
  1471.  
  1472. =item RPC::XML::datetime_iso8601
  1473.  
  1474. Creates an instance of the XML-RPC C<dateTime.iso8601> type. The specification
  1475. for ISO 8601 may be found elsewhere. No processing is done to the data.
  1476.  
  1477. =item RPC::XML::base64
  1478.  
  1479. Creates an object that encapsulates a chunk of data that will be treated as
  1480. base-64 for transport purposes. The value may be passed in as either a string
  1481. or as a scalar reference. Additionally, a second (optional) parameter may be
  1482. passed, that if true identifies the data as already base-64 encoded. If so,
  1483. the data is decoded before storage. The C<value> method returns decoded data,
  1484. and the C<as_string> method encodes it before stringification.
  1485.  
  1486. Alternately, the constructor may be given an open filehandle argument instead
  1487. of direct data. When this is the case, the data is never read into memory in
  1488. its entirety, unless the C<value> or C<as_string> methods are called. This
  1489. allows the manipulation of arbitrarily-large Base-64-encoded data chunks. In
  1490. these cases, the flag (optional second argument) is still relevant, but the
  1491. data is not pre-decoded if it currently exists in an encoded form. It is only
  1492. decoded as needed. Note that the filehandle passed must be open for reading,
  1493. at least. It will not be written to, but it will be read from. The position
  1494. within the file will be preserved between operations.
  1495.  
  1496. Because of this, this class supports a special method called C<to_file>, that
  1497. takes one argument. The argument may be either an open, writable filehandle or
  1498. a string. If it is a string, C<to_file> will attempt to open it as a file and
  1499. write the I<decoded> data to it. If the argument is a an open filehandle, the
  1500. data will be written to it without any pre- or post-adjustment of the handle
  1501. position (nor will it be closed upon completion). This differs from the
  1502. C<serialize> method in that it always writes the decoded data (where the other
  1503. always writes encoded data), and in that the XML opening and closing tags are
  1504. not written. The return value of C<to_file> is the size of the data written
  1505. in bytes.
  1506.  
  1507. =item RPC::XML::array
  1508.  
  1509. Creates an array object. The constructor takes zero or more data-type
  1510. instances as arguments, which are inserted into the array in the order
  1511. specified. C<value> returns an array reference of native Perl types. If a
  1512. non-null value is passed as an argument to C<value()>, then the array
  1513. reference will contain datatype objects (a shallow rather than deep copy).
  1514.  
  1515. =item RPC::XML::struct
  1516.  
  1517. Creates a struct object, the analogy of a hash table in Perl. The keys are
  1518. ordinary strings, and the values must all be data-type objects. The C<value>
  1519. method returns a hash table reference, with native Perl types in the values.
  1520. Key order is not preserved. Key strings are now encoded for special XML
  1521. characters, so the use of such (C<E<lt>>, C<E<gt>>, etc.) should be
  1522. transparent to the user. If a non-null value is passed as an argument to
  1523. C<value()>, then the hash reference will contain the datatype objects rather
  1524. than native Perl data (a shallow vs. deep copy, as with the array type above).
  1525.  
  1526. When creating B<RPC::XML::struct> objects, there are two ways to pass the
  1527. content in for the new object: Either an existing hash reference may be passed,
  1528. or a series of key/value pairs may be passed. If a reference is passed, the
  1529. existing data is copied (the reference is not re-blessed), with the values
  1530. encoded into new objects as needed.
  1531.  
  1532. =item RPC::XML::fault
  1533.  
  1534. A fault object is a special case of the struct object that checks to ensure
  1535. that there are two keys, C<faultCode> and C<faultString>.
  1536.  
  1537. As a matter of convenience, since the contents of a B<RPC::XML::fault>
  1538. structure are specifically defined, the constructor may be called with exactly
  1539. two arguments, the first of which will be taken as the code, and the second
  1540. as the string. They will be converted to RPC::XML types automatically and
  1541. stored by the pre-defined key names.
  1542.  
  1543. Also as a matter of convenience, the fault class provides the following
  1544. accessor methods for directly retrieving the integer code and error string
  1545. from a fault object:
  1546.  
  1547. =over 4
  1548.  
  1549. =item code
  1550.  
  1551. =item string
  1552.  
  1553. =back
  1554.  
  1555. Both names should be self-explanatory. The values returned are Perl values,
  1556. not B<RPC::XML> class instances.
  1557.  
  1558. =back
  1559.  
  1560. =head2 Message Classes
  1561.  
  1562. The message classes are used both for constructing messages for outgoing
  1563. communication as well as representing the parsed contents of a received
  1564. message. Both implement the following methods:
  1565.  
  1566. =over 4
  1567.  
  1568. =item new
  1569.  
  1570. This is the constructor method for the two message classes. The response class
  1571. may have only a single value (as a response is currently limited to a single
  1572. return value), and requests may have as many arguments as appropriate. In both
  1573. cases, the arguments are passed to the exported C<smart_encode> routine
  1574. described earlier.
  1575.  
  1576. =item as_string
  1577.  
  1578. Returns the message object expressed as an XML document. The document will be
  1579. lacking in linebreaks and indention, as it is not targeted for human reading.
  1580.  
  1581. =item serialize($filehandle)
  1582.  
  1583. Serialize the message to the given file-handle. This avoids creating the entire
  1584. XML message within memory, which may be relevant if there is especially-large
  1585. Base-64 data within the message.
  1586.  
  1587. =item length
  1588.  
  1589. Returns the total size of the message in bytes, used by the client and server
  1590. classes to set the Content-Length header.
  1591.  
  1592. =back
  1593.  
  1594. The two message-object classes are:
  1595.  
  1596. =over 4
  1597.  
  1598. =item RPC::XML::request
  1599.  
  1600. This creates a request object. A request object expects the first argument to
  1601. be the name of the remote routine being called, and all remaining arguments
  1602. are the arguments to that routine. Request objects have the following methods
  1603. (besides C<new> and C<as_string>):
  1604.  
  1605. =over 4
  1606.  
  1607. =item name
  1608.  
  1609. The name of the remote routine that the request will call.
  1610.  
  1611. =item args
  1612.  
  1613. Returns a list reference with the arguments that will be passed. No arguments
  1614. will result in a reference to an empty list.
  1615.  
  1616. =back
  1617.  
  1618. =item RPC::XML::response
  1619.  
  1620. The response object is much like the request object in most ways. It may
  1621. take only one argument, as that is all the specification allows for in a
  1622. response. Responses have the following methods (in addition to C<new> and
  1623. C<as_string>):
  1624.  
  1625. =over 4
  1626.  
  1627. =item value
  1628.  
  1629. The value the response is returning. It will be a RPC::XML data-type.
  1630.  
  1631. =item is_fault
  1632.  
  1633. A boolean test whether or not the response is signalling a fault. This is
  1634. the same as taking the C<value> method return value and testing it, but is
  1635. provided for clarity and simplicity.
  1636.  
  1637. =back
  1638.  
  1639. =back
  1640.  
  1641. =head1 DIAGNOSTICS
  1642.  
  1643. All constructors (in all data classes) return C<undef> upon failure, with the
  1644. error message available in the package-global variable B<C<$RPC::XML::ERROR>>.
  1645.  
  1646. =head1 GLOBAL VARIABLES
  1647.  
  1648. The following global variables may be changed to control certain behavior of
  1649. the library. All variables listed below may be imported into the application
  1650. namespace when you C<use> B<RPC::XML>:
  1651.  
  1652. =over 4
  1653.  
  1654. =item $ENCODING
  1655.  
  1656. This variable controls the character-set encoding reported in outgoing XML
  1657. messages. It defaults to C<us-ascii>, but may be set to any value recognized
  1658. by XML parsers.
  1659.  
  1660. =item $FORCE_STRING_ENCODING
  1661.  
  1662. By default, C<smart_encode> uses heuristics to determine what encoding
  1663. is required for a data type. For example, C<123> would be encoded as C<int>,
  1664. where C<3.14> would be encoded as C<double>. In some situations it may be
  1665. handy to turn off all these heuristics, and force encoding of C<string> on
  1666. all data types encountered during encoding. Setting this flag to C<true>
  1667. will do just that.
  1668.  
  1669. Defaults to C<false>.
  1670.  
  1671. =back
  1672.  
  1673. =head1 CAVEATS
  1674.  
  1675. This began as a reference implementation in which clarity of process and
  1676. readability of the code took precedence over general efficiency. It is now
  1677. being maintained as production code, but may still have parts that could be
  1678. written more efficiently.
  1679.  
  1680. =head1 CREDITS
  1681.  
  1682. The B<XML-RPC> standard is Copyright (c) 1998-2001, UserLand Software, Inc.
  1683. See L<http://www.xmlrpc.com> for more information about the B<XML-RPC>
  1684. specification.
  1685.  
  1686. =head1 LICENSE
  1687.  
  1688. This module and the code within are released under the terms of the Artistic
  1689. License 2.0
  1690. (http://www.opensource.org/licenses/artistic-license-2.0.php). This code may
  1691. be redistributed under either the Artistic License or the GNU Lesser General
  1692. Public License (LGPL) version 2.1
  1693. (http://www.opensource.org/licenses/lgpl-license.php).
  1694.  
  1695. =head1 SEE ALSO
  1696.  
  1697. L<RPC::XML::Client>, L<RPC::XML::Server>, L<RPC::XML::Parser>, L<XML::Parser>
  1698.  
  1699. =head1 AUTHOR
  1700.  
  1701. Randy J. Ray <rjray@blackperl.com>
  1702.  
  1703. =cut
  1704.